package com.qipay.admin.cp.controller;

import com.qipay.admin.BaseController;
import com.qipay.admin.cp.vo.CpChannelPostDTO;
import com.qipay.admin.cp.vo.CpPostDTO;
import com.qipay.admin.login.AuthPassport;
import com.qipay.admin.tags.PageModel;
import com.qipay.admin.utils.CpInfoBuilder;
import com.qipay.admin.utils.SiteHelper;
import com.qipay.baas.model.*;
import com.qipay.channelType.ChannelTypeService;
import com.qipay.core.entity.Pagination;
import com.qipay.cp.CpService;
import com.qipay.cpaccount.CpAccountService;
import com.qipay.cpchannel.service.CpChannelService;
import com.qipay.cpinfo.service.CpInfoService;
import com.qipay.order.service.OrderService;
import com.qipay.security.UserDetailsServiceImpl;
import com.qipay.user.entity.UserLevel;
import com.qipay.user.service.UserService;
import com.qipay.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Controller
public class CPController extends BaseController {

    @Autowired
    CpService cpService;
    @Autowired
    CpInfoService cpInfoService;
    @Autowired
    CpInfoBuilder cpInfoBuilder;
    @Autowired
    CpChannelService cpChannelService;
    @Autowired
    CpAccountService cpAccountService;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;

    @Autowired
    ChannelTypeService channelTypeService;


    /**
     * 渠道以及费率管理---列表
     *
     * @param loginUser
     * @return
     * @throws UnsupportedEncodingException
     */
    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/proxy/channelType"}, method = RequestMethod.GET)
    public ModelAndView channelTypeList(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser
    ) throws UnsupportedEncodingException {
        List<ChannelType> channelTypes = channelTypeService.selectAll();
        ModelAndView view = createModelAndView("channel-type-feeRate");
        view.addObject("list", channelTypes);
        return view;
    }

    /**
     * 一次性改掉商户费率
     *
     * @param loginUser
     * @return
     * @throws UnsupportedEncodingException
     */
    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/proxy/test"}, method = RequestMethod.GET)
    public void test(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser
    ) throws UnsupportedEncodingException {
        List<Cp> cps = cpService.findAll();
        for (Cp c : cps) {
            List<CpChannel> cpChannels = cpChannelService.selectByCpId(c.getId(), 1, 30);
            for (CpChannel cc : cpChannels) {
                ChannelType channelType = channelTypeService.findById(cc.getChannelType());
                if (c.getType() == 2) {//代理商
                    cc.setFeeRecharge(channelType.getAgentFeeRecharge());
                } else {
                    cc.setFeeRecharge(channelType.getCpFeeRecharge());
                }
                cpChannelService.update(cc);
            }
        }

    }

    /**
     * 渠道以及费率管理---保存
     *
     * @param loginUser
     * @param channelType
     * @return
     * @throws UnsupportedEncodingException
     */
    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/proxy/channelTypeSave"}, method = RequestMethod.POST)
    public ModelAndView channelTypeSave(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                        ChannelType channelType
    ) throws UnsupportedEncodingException {
        //设置商户费率的格式显示为当前费率除以100
        channelType.setCpFeeRecharge(channelType.getCpFeeRecharge().divide(new BigDecimal(String.valueOf("100"))));
        //设置代理商费率的格式显示为当前费率除以100
        channelType.setAgentFeeRecharge(channelType.getAgentFeeRecharge().divide(new BigDecimal(String.valueOf("100"))));
        //设置垫资比的格式显示为当前费率除以100
//        channelType.setRateAdvance(channelType.getRateAdvance().divide(new BigDecimal(String.valueOf("100"))));
        //判断传进来的渠道id不为空
        if (channelType.getId() != null) {
            //符合条件，将id、cp_fee_recharge、agent_fee_recharge、rate_advance等字段的数据保存到channeltype表中
            channelTypeService.save(channelType.getId(), channelType.getCpFeeRecharge(), channelType.getAgentFeeRecharge(), channelType.getRateAdvance());

            if (channelType.getCpFeeRecharge() != null) {
                channelTypeService.updateCpFeeRechargeByid(channelType.getId(), channelType.getCpFeeRecharge());
            }

            if (channelType.getAgentFeeRecharge() != null) {
                channelTypeService.updateAgentFeeRechargeByid(channelType.getId(), channelType.getAgentFeeRecharge());
            }

            if (channelType.getRateAdvance() != null) {
                channelTypeService.updateRateAdvanceByid(channelType.getId(), channelType.getRateAdvance());
            }
        } else {
            //如果不符合，则将数据插入到数据库中
            channelTypeService.insert(channelType);
        }
        //查询渠道表中的所有数据，并以集合的方式接收数据
        List<ChannelType> channelTypes = channelTypeService.selectAll();
        //创建渠道以及费率管理视图，视图名就是jsp名
        ModelAndView view = createModelAndView("channel-type-feeRate");
        //将查询出来的集合放入到视图中，通过视图传输数据到指定的jsp
        view.addObject("list", channelTypes);

        List<Cp> cps = cpService.findAll();
        for (Cp c : cps) {
            CpChannel cpChannel = cpChannelService.getByCpIdAndChannelType(c.getId(), channelType.getId().byteValue());
            if (cpChannel != null) {
                if (c.getType() == 2) {//代理商
                    cpChannel.setFeeRecharge(channelType.getAgentFeeRecharge());
                } else {
                    cpChannel.setFeeRecharge(channelType.getCpFeeRecharge());
                }
                cpChannel.setRateAdvince(channelType.getRateAdvance());
                cpChannelService.update(cpChannel);
            }
        }

        return view;
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/proxy", "/proxy/list", "/proxy/lst"}, method = RequestMethod.GET)
    public ModelAndView listProxy(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                  @RequestParam(value = "cpId", required = false, defaultValue = "") Long cpId,
                                  @RequestParam(value = "name", required = false, defaultValue = "") String name,
                                  @RequestParam(value = "person", required = false, defaultValue = "") String person,
                                  @RequestParam(value = "contact", required = false, defaultValue = "") String contact,
                                  @RequestParam(value = "m", required = false, defaultValue = "") String m,
                                  @RequestParam(value = "s", required = false, defaultValue = "") Byte state,
                                  @RequestParam(value = "p", required = false, defaultValue = "0") int p,
                                  @RequestParam(value = "pz", required = false, defaultValue = "10") int pz,
                                  @RequestParam(value = "agent", required = false, defaultValue = "1") byte agent
    ) throws UnsupportedEncodingException {
        return list(loginUser, cpId, name, person, contact, m, state, p, pz, (byte) 1);
    }

    @AuthPassport(key = "agent")
    @RequestMapping(value = {"/cp", "/cp/lst", "/cp/list"}, method = RequestMethod.GET)
    public ModelAndView list(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                             @RequestParam(value = "cpId", required = false, defaultValue = "") Long cpId,
                             @RequestParam(value = "name", required = false, defaultValue = "") String name,
                             @RequestParam(value = "person", required = false, defaultValue = "") String person,
                             @RequestParam(value = "contact", required = false, defaultValue = "") String contact,
                             @RequestParam(value = "m", required = false, defaultValue = "") String m,
                             @RequestParam(value = "s", required = false, defaultValue = "") Byte state,
                             @RequestParam(value = "p", required = false, defaultValue = "0") int p,
                             @RequestParam(value = "pz", required = false, defaultValue = "10") int pz,
                             @RequestParam(value = "agent", required = false, defaultValue = "0") byte agent
    ) throws UnsupportedEncodingException {
        Pagination pagination = Pagination.instance(p, pz);

        ModelAndView view = agent == 1 ? createModelAndView("proxy-lst") : createModelAndView("cp-lst");
        UserLevel level = loginUser.getLevel();
        List<CpAccount> lst = null;
        long total = 0;
        byte type = 1;
        if (level == UserLevel.ADMIN) {
            /*agent=1表示代理商，agent=0表示普通商户*/
            if (agent == 1) {
                type = 2; //*agent=1表示代理商
            }
            total = cpInfoService.countByConditionAndTypeAgentId(type, cpId, null, name, person, contact, m, state);
            if (total > 0) {
                if (type == 1) {
                    //管理员查看普通商户的列表
                    lst = cpService.allCpList(name, cpId, person, contact, type, 0l, pagination);
                } else {
                    //管理员查看代理商的列表
                    lst = cpService.allAgentList(name, cpId, person, contact, type, 0l, pagination);
                }

            }

        }

        if (level == UserLevel.AGENT) {
            long cpIdNow = Long.valueOf(loginUser.getUsername());
            //only see current agant`s child cp list.
            total = cpInfoService.countByConditionAndTypeAgentId(type, cpId, cpIdNow, name, person, contact, m, state);
            if (total > 0) {
                lst = cpService.allCpList(name, cpId, person, contact, type, cpIdNow, pagination);
            }
        }
        Long totalAgent = 0L;//总额--订单表的agent-fee
        Long feeAgent = 0L;//手续费---代理商提现手续费
        Long widthAgent = 0L;//提现---提现列表
        Long disTotal = 0L;
        //可用余额添加
        if(lst != null&& lst.size() > 0 ){
            for (CpAccount cpa : lst) {
                cpa.setBalanceDisabled(cpa.getBalanceDisabled()==null?0:cpa.getBalanceDisabled());
                cpa.setTotal(cpa.getTotal()==null?0:cpa.getTotal());
                cpa.setWidthdrawAmount(cpa.getWidthdrawAmount()==null?0:cpa.getWidthdrawAmount());
                cpa.setBalance(cpa.getBalance()==null?0:cpa.getBalance());
                cpa.setWithdrawFee(cpa.getWithdrawFee()==null?0:cpa.getWithdrawFee());
                cpa.setWidthdrawAmount(cpa.getWidthdrawAmount()==null?0:cpa.getWidthdrawAmount());
            }
            if (type == 1) {
                for (CpAccount cpa : lst) {
                    cpa.setBalanceAvailable(cpa.getTotal() - cpa.getWidthdrawAmount() - cpa.getBalanceDisabled());
                    cpa.setBalance(cpa.getTotal() - cpa.getWidthdrawAmount());
                    cpa.setBalanceAdvance(0L);
                }
            } else {
                for (CpAccount cpa : lst) {
                    cpa.setBalanceAvailable(cpa.getFee() - cpa.getAgentFee() - cpa.getWidthdrawAmount() - cpa.getWithdrawFee());
                    cpa.setBalance(cpa.getFee() - cpa.getAgentFee() - cpa.getWidthdrawAmount() - cpa.getWithdrawFee());
                    cpa.setBalanceAdvance(0L);
                    cpa.setFee(cpa.getWithdrawFee());
                    totalAgent = +cpa.getBalance();
                    feeAgent = +cpa.getWithdrawFee();
                    widthAgent = +cpa.getWidthdrawAmount();
                    disTotal = +cpa.getBalanceDisabled();
                }
            }
        }


        //统计部分
        CpAccount tj = null;
        if (type == 1) {
            if (level == UserLevel.AGENT) {
                long agentId = Long.valueOf(loginUser.getUsername());
                tj = cpService.allCpListTj(agentId);
            } else {
                tj = cpService.allCpListTj();
            }
            tj.setBalance(tj.getTotal() - tj.getWidthdrawAmount());
            tj.setBalanceAvailable(tj.getTotal() - tj.getWidthdrawAmount() - tj.getBalanceDisabled());
            tj.setBalanceAdvance(0L);
        } else {
            tj = new CpAccount();
            tj.setFee(feeAgent);
            tj.setBalance(totalAgent - widthAgent - feeAgent - widthAgent);
            tj.setBalanceAvailable(totalAgent - widthAgent - feeAgent - widthAgent - disTotal);
            tj.setWidthdrawAmount(widthAgent);
            tj.setBalanceAdvance(0L);
            tj.setBalanceDisabled(disTotal);
        }

        view.addObject("total", total);
        view.addObject("lst", lst);//商户列表数据
        view.addObject("totalList", tj);//统计表头

        PageModel pageModel = new PageModel();
        pageModel.setPage(p);
        pageModel.setPageSize(pz);

        if (name != null) {
            name = URLEncoder.encode(name, "utf8");
        }
        if (person != null) {
            name = URLEncoder.encode(person, "utf8");
        }
        if (contact != null) {
            name = URLEncoder.encode(contact, "utf8");
        }

        pageModel.setUrl(String.format("?name=%s&cpId=%s&person=%s&contact=%s&m=%s&agent=", name, cpId == null ? "" : cpId, person, contact, m, agent));
        pageModel.setTotal(total);
        view.addObject("page", pageModel);
        return view;
    }

    @AuthPassport(key = "agent")
    @RequestMapping(value = {"/proxy/{cpId:[\\d]+}/child"}, method = RequestMethod.GET)
    public ModelAndView proxyChild(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                   @PathVariable @NotNull Long cpId,
                                   @RequestParam(value = "p", required = false, defaultValue = "0") int p,
                                   @RequestParam(value = "pz", required = false, defaultValue = "10") int pz) {
        ModelAndView view = createModelAndView("proxy-child-lst");
        Pagination pagination = Pagination.instance(p, pz);
        CpInfo cpInfo = cpInfoService.get(cpId);
        List<CpAccount> lst = null;
        long total = 0;
        byte type4cp = 1;
        //only see current agant`s child cp list.
        total = cpInfoService.countByConditionAndTypeAgentId(type4cp, null, cpId, null, null, null, null, null);
        if (total > 0) {
//            lstDb = cpInfoService.getByConditionAndTypeAgentId(type4cp, null, cpId, null, null, null, null, null, p, pz);
            lst = cpService.allCpList(null, null, null, null, type4cp, cpId, pagination);
        }
        if (lst != null && lst.size() > 0) {
            for (CpAccount cpa : lst) {
                cpa.setBalanceAvailable(cpa.getTotal() - cpa.getWidthdrawAmount());
                cpa.setBalance(cpa.getTotal() - cpa.getWidthdrawAmount());
                cpa.setBalanceAdvance(0L);
            }
        }
        view.addObject("lst", lst);//商户列表数据
        view.addObject("detail", cpInfo);//商户列表数据

        PageModel pageModel = new PageModel();
        pageModel.setPage(p);
        pageModel.setPageSize(pz);
        pageModel.setTotal(total);
        pageModel.setUrl("/proxy/" + cpId + "/child");
        view.addObject("page", pageModel);

        return view;
    }


    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/proxy/{cpId:[\\d]+}"}, method = RequestMethod.GET)
    public ModelAndView detailProxy(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                    @PathVariable @NotNull Long cpId,
                                    @RequestParam(value = "agent", required = false, defaultValue = "1") byte agent) {
        return detail(loginUser, cpId, (byte) 1);
    }

    @AuthPassport(key = "agent")
    @RequestMapping(value = {"/cp/{cpId:[\\d]+}"}, method = RequestMethod.GET)
    public ModelAndView detail(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                               @PathVariable @NotNull Long cpId,
                               @RequestParam(value = "agent", required = false, defaultValue = "0") byte agent) {
        ModelAndView view = createModelAndView("cp-detail");
        view.addObject("admin", loginUser);
        view.addObject("proxies", cpService.findByType((byte) 2, 1, 10000));
        if (loginUser.getLevel() == UserLevel.AGENT) {
            Cp cp = cpService.getOneById(loginUser.getCpId());
            if (cp != null) {
                cp.setFeeDefaultRecharge(cp.getFeeDefaultRecharge().multiply(SiteHelper.decimalFor100));
//                cp.setFeeWithdrawAdvince(cp.getFeeWithdrawAdvince().multiply(SiteHelper.decimalFor100));
                cp.setCostWithdraw(cp.getCostWithdraw() / 100);
                view.addObject("agentModel", cp);
            }
        }

        if (cpId == null || cpId < 1) {
            view.addObject("appid", orderService.createOrder());
            view.addObject("secretid", orderService.createOrder());
            view.addObject("isadd", "1");
            view.addObject("agent", String.valueOf(agent));

            return view;
        } else {
            CpInfo cpInfo = cpInfoService.get(cpId);
            Cp cp = cpService.getOneById(cpId);
            CpPostDTO dto = new CpPostDTO();
            if (cpInfo != null && cp != null) {
//                if(cp.getAgentId()!=null&&cp.getAgentId().longValue()>0){
//
//                }
                agent = cp.getType() == 2 ? (byte) 1 : (byte) 0;
                BeanUtils.copyProperties(cp, dto);
                BeanUtils.copyProperties(cpInfo, dto);
                view.addObject("isadd", "0");
                dto.setFeeDefaultRecharge(dto.getFeeDefaultRecharge().multiply(SiteHelper.decimalFor100));
//                dto.setFeeWithdrawAdvince(dto.getFeeWithdrawAdvince().multiply(SiteHelper.decimalFor100));
                dto.setCostWithdraw(dto.getCostWithdraw() / 100);
                view.addObject("detail", dto);
                view.addObject("agent", String.valueOf(agent));

                return view;
            }
        }
        return new ModelAndView(agent == 1 ? "redirect:/proxy" : "redirect:/cp");
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/proxy/save"}, method = RequestMethod.POST)
    public String saveProxy(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                            CpPostDTO dto,
                            @RequestParam(value = "agent", required = false, defaultValue = "1") byte agent) {
        return save(loginUser, dto, (byte) 1);
    }

    @AuthPassport(key = "agent")
    @RequestMapping(value = {"/cp/save"}, method = RequestMethod.POST)
    public String save(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                       CpPostDTO dto,
                       @RequestParam(value = "agent", required = false, defaultValue = "0") byte agent) {
        boolean isAgent = agent == 1;
        if (dto != null) {
            dto.setFeeDefaultRecharge(dto.getFeeDefaultRecharge().divide(SiteHelper.decimalFor100));
            //垫资提现费率
//            dto.setFeeWithdrawAdvince(dto.getFeeWithdrawAdvince().divide(SiteHelper.decimalFor100));
            if (dto.getId() != null && dto.getId() > 0) {
                long cpId = dto.getCpId();
                CpInfo cpInfo = cpInfoService.get(cpId);
                Cp cp = cpService.getOneById(cpId);

                cp.setFeeDefaultRecharge(dto.getFeeDefaultRecharge());
                cp.setCostWithdraw(dto.getCostWithdraw());
                cp.setFeeWithdrawAdvince(dto.getFeeWithdrawAdvince());
                cp.setAgentId(dto.getAgentId());
                cp.setBindMobile(dto.getBindMobile());

                BeanUtils.copyProperties(dto, cpInfo);
                cpService.update(cp);
                cpInfoService.update(cpInfo);
            } else {
                //add
                CpInfo cpInfo = new CpInfo();
                Cp cp = new Cp();
                BeanUtils.copyProperties(dto, cp);
                cp.setAppId(orderService.createOrder());
                cp.setAccountState((byte) 2);
                cp.setContractState((byte) 0);
                cp.setCreateTime(new Date());


                cpService.insert(cp);
                if (cp.getId() != null && cp.getId() > 0) {
                    BeanUtils.copyProperties(dto, cpInfo);
                    cpInfo.setCpId(cp.getId());
                    cpInfoService.insert(cpInfo);
                    CpAccount cpAccount = new CpAccount();
                    long defaultVal = 0;
                    cpAccount.setBalance(defaultVal);
                    cpAccount.setBalanceAdvance(defaultVal);
                    cpAccount.setBalanceAvailable(defaultVal);
                    cpAccount.setBalanceDisabled(defaultVal);
                    cpAccount.setCpId(cp.getId());
                    cpAccount.setBalanceAdvanceWidthdraw(defaultVal);
                    cpAccountService.create(cpAccount);
                    User user = new User();
                    String cpId = cp.getId().toString();
                    user.setName(cpId);
                    user.setSex((byte) 1);
                    user.setPwd(passwordEncoder.encode(cpId));
                    user.setPid(cp.getAgentId() != null ? cp.getAgentId().intValue() : 0);
                    user.setLevel(1);
                    if (cp.getType() == 2) {
                        //cp
                        user.setLevel(200);
                        user.setPid(0);
                    }
                    userService.insert(user);
                }

            }
        }
        return isAgent ? "redirect:/proxy" : "redirect:/cp";
    }


    /**
     * 代理商查看自己的chanel列表
     * @param loginUser
     * @param cpId
     * @param p
     * @param pz
     * @return
     */
    @AuthPassport(key = "agent")
    @RequestMapping(value = {"/proxy/{cpId:[\\d]+}/channel"}, method = RequestMethod.GET)
    public ModelAndView listProxyChannel(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                         @PathVariable @NotNull Long cpId,
                                         @RequestParam(value = "p", required = false, defaultValue = "0") int p,
                                         @RequestParam(value = "pz", required = false, defaultValue = "10") int pz) {
        return listChannel(loginUser, cpId, p, pz, (byte) 1);
    }

    /**
     * cp查看自己的chanel列表
     * @param loginUser
     * @param cpId
     * @param p
     * @param pz
     * @param agent
     * @return
     */
    @AuthPassport(key = "cp")
    @RequestMapping(value = {"/cp/{cpId:[\\d]+}/channel"}, method = RequestMethod.GET)
    public ModelAndView listChannel(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                    @PathVariable @NotNull Long cpId,
                                    @RequestParam(value = "p", required = false, defaultValue = "0") int p,
                                    @RequestParam(value = "pz", required = false, defaultValue = "10") int pz,
                                    @RequestParam(value = "agent", required = false, defaultValue = "0") byte agent) {
        boolean isAgent = agent == 1;
        ModelAndView view = createModelAndView("cp-channel-lst");
        view.addObject("lst", cpChannelService.selectByCpId(cpId, p, pz));
        CpInfo cpInfo = cpInfoService.get(cpId);
        Cp cp = cpService.getOneById(cpId);
        if (cpInfo != null) {
            view.addObject("detail", cpInfo);
            view.addObject("cpType", cp.getType());
            return view;
        } else {
            return new ModelAndView(isAgent ? "redirect:/proxy" : "redirect:/cp");
        }

    }

    @AuthPassport(key = "agent")
    @RequestMapping(value = {"/proxy/channel/{id:[\\d]+}"}, method = RequestMethod.GET)
    public ModelAndView detailProxyChannel(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                           @PathVariable @NotNull Long id) {
        return detailChannel(loginUser, id, (byte) 1);
    }

    /**修改*/
    @AuthPassport(key = "cp")
    @RequestMapping(value = {"/cp/channel/{id:[\\d]+}"}, method = RequestMethod.GET)
    public ModelAndView detailChannel(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                      @PathVariable @NotNull Long id,
                                      @RequestParam(value = "agent", required = false, defaultValue = "0") byte agent) {
        ModelAndView view = createModelAndView("cp-channel-detail");
        boolean isAgent = agent == 1;
        if (id == null || id < 1) {
            return new ModelAndView(isAgent ? "redirect:/proxy/channel/add" : "redirect:/cp/channel/add");
        }
        CpChannel cpChannel = cpChannelService.get(id);
        List<ChannelType> channelTypes = channelTypeService.selectAll();
        view.addObject("channelTypes",channelTypes);
        if (cpChannel != null) {
            cpChannel.setFeeRecharge(cpChannel.getFeeRecharge().multiply(SiteHelper.decimalFor100));
//            cpChannel.setRateAdvince(cpChannel.getRateAdvince().multiply(SiteHelper.decimalFor100));
            view.addObject("isadd", "0");
            view.addObject("detail", cpChannel);
            CpInfo cpInfo = cpInfoService.get(cpChannel.getCpId());
            Cp cp = cpService.getOneById(cpChannel.getCpId());
            if (cpInfo != null) {
                view.addObject("detailInfo", cpInfo);
                view.addObject("detailCp", cp);
                if (cp.getType() == 1 && cp.getAgentId() != null && cp.getAgentId().longValue() > 0) {
                    Cp cpProxy = cpService.getOneById(cp.getAgentId().longValue());
                    view.addObject("agentChannels", cpChannelService.selectByCpId(cp.getAgentId(), 1, 1000));
                    view.addObject("detailCpParent", cpProxy);
                }
                return view;
            }
            return view;
        }
        return new ModelAndView(isAgent ? "redirect:/proxy" : "redirect:/cp");

    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/proxy/channel/add"}, method = RequestMethod.GET)
    public ModelAndView detailProxyChannelAdd(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                              @RequestParam(value = "cpid", required = false, defaultValue = "0") long cpId) {
        return detailChannelAdd(loginUser, cpId, (byte) 1);
    }

    @AuthPassport(key = "agent")
    @RequestMapping(value = {"/cp/channel/add"}, method = RequestMethod.GET)
    public ModelAndView detailChannelAdd(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                         @RequestParam(value = "cpid", required = false, defaultValue = "0") long cpId,
                                         @RequestParam(value = "agent", required = false, defaultValue = "0") byte agent) {
        ModelAndView view = createModelAndView("cp-channel-detail");
        view.addObject("isadd", "1");
        boolean isAgent = agent == 1;
        CpInfo cpInfo = cpInfoService.get(cpId);
        Cp cp = cpService.getOneById(cpId);
        List<ChannelType> channelTypes = channelTypeService.selectAll();
        view.addObject("channelTypes",channelTypes);
        if (cpInfo != null) {
            view.addObject("detailInfo", cpInfo);
            view.addObject("detailCp", cp);

            if (cp.getType() == 1 && cp.getAgentId() != null && cp.getAgentId().longValue() > 0) {
                Cp cpProxy = cpService.getOneById(cp.getAgentId().longValue());
                view.addObject("agentChannels", cpChannelService.selectByCpId(cp.getAgentId(), 1, 1000));
                view.addObject("detailCpParent", cpProxy);
            }
            return view;
        } else {
            return new ModelAndView(isAgent ? "redirect:/proxy" : "redirect:/cp");
        }
    }

    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/proxy/channel/save"}, method = RequestMethod.POST)
    public String saveProxyChannel(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                   CpChannelPostDTO dto) {
        return saveChannel(loginUser, dto, (byte) 1);
    }


    @AuthPassport(key = "agent")
    @RequestMapping(value = {"/cp/channel/save"}, method = RequestMethod.POST)
    public String saveChannel(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                              CpChannelPostDTO dto,
                              @RequestParam(value = "agent", required = false, defaultValue = "0") byte agent) {
        boolean isAgent = agent == 1;

//        CpChannel cpChannel = cpChannelService.getByCpIdAndChannelType(dto.getCpId(), dto.getChannelType());
//        if(cpChannel!=null&&)

        if (dto.getId() != null && dto.getId().longValue() > 0) {
            CpChannel db = cpChannelService.get(dto.getId());
            if (db != null && db.getId() > 0) {
                if (agent < 1) {
                    Cp cp = cpService.getOneById(db.getCpId());
                    //给CP的支付方式添加费率时， 要高于当前这个代理商这个支付方式的费率
                    if (cp.getType() == 1 && cp.getAgentId() != null && cp.getAgentId().longValue() > 0) {
                        CpChannel cpChannelProxy = cpChannelService.getByCpIdAndChannelType(cp.getAgentId(), dto.getChannelType());
                        if (cpChannelProxy != null) {
                            if (dto.getFeeRecharge().compareTo(cpChannelProxy.getFeeRecharge().multiply(SiteHelper.decimalFor100)) < 0) {
                                return String.format("redirect:/cp/channel/%s?cpid=%s&error=1", dto.getId().toString(), dto.getCpId().toString());
                            }
                            if (loginUser.getLevel() == UserLevel.AGENT) {
                                //代理商为商户添加垫支时，使用代理的垫支，管理员用他输入的。
//                                dto.setRateAdvince(cpChannelProxy.getRateAdvince());
                            }
                        }
                    }
                }
                BeanUtils.copyProperties(dto, db);
                db.setUpdateDate(new Date());
                db.setFeeRecharge(db.getFeeRecharge().divide(SiteHelper.decimalFor100));
//                db.setRateAdvince(db.getRateAdvince().divide(SiteHelper.decimalFor100));
                cpChannelService.update(db);
            }

        } else {
            CpChannel db = new CpChannel();
            BeanUtils.copyProperties(dto, db);
            if (agent < 1) {
                //给CP的支付方式添加费率时， 要高于当前这个代理商这个支付方式的费率
                Cp cp = cpService.getOneById(db.getCpId());
                if (cp.getAgentId() != null && cp.getAgentId().longValue() > 0) {
                    CpChannel cpChannelProxy = cpChannelService.getByCpIdAndChannelType(cp.getAgentId(), dto.getChannelType());
                    if (cpChannelProxy != null) {
                        if (dto.getFeeRecharge().compareTo(cpChannelProxy.getFeeRecharge().multiply(SiteHelper.decimalFor100)) < 0) {
                            return String.format("redirect:/cp/channel/add?cpid=%s&error=1", dto.getCpId().toString());
                        }
                        //if(loginUser.getLevel()==UserLevel.AGENT){
                        //代理商为商户添加垫支时，使用代理的垫支，管理员用他输入的。
//                        dto.setRateAdvince(cpChannelProxy.getRateAdvince());
//                        db.setRateAdvince(dto.getRateAdvince());
                        //}
                    }
                } else {
//                    db.setRateAdvince(dto.getRateAdvince().divide(SiteHelper.decimalFor100));

                }
                //是否是代理商，根据类型查询
                ChannelType channelType = channelTypeService.findById(db.getChannelType());
                if (cp.getType() == 2) {
                    db.setFeeRecharge(channelType.getAgentFeeRecharge());
                } else {
                    db.setFeeRecharge(channelType.getCpFeeRecharge());
                }
            }
            //db.setFeeRecharge(dto.getFeeRecharge().divide(SiteHelper.decimalFor100));
            //db.setRateAdvince(dto.getRateAdvince().divide(SiteHelper.decimalFor100));
            //db.setRateAdvince(new BigDecimal(String.valueOf("0.5")));
            db.setUpdateDate(new Date());
            db.setCreateDate(new Date());

            cpChannelService.insert(db);

        }
        return String.format(isAgent ? "redirect:/proxy/%s/channel" : "redirect:/cp/%s/channel", dto.getCpId().toString());
    }

    @RequestMapping(value = {"cpinfo"})
    @ResponseBody
    public Result<List<CpInfo>> testCpInfo(@RequestParam(value = "name", required = false, defaultValue = "") String name,
                                           @RequestParam(value = "person", required = false, defaultValue = "") String person,
                                           @RequestParam(value = "contact", required = false, defaultValue = "") String contact,
                                           @RequestParam(value = "m", required = false, defaultValue = "") String m,
                                           @RequestParam(value = "p", required = false, defaultValue = "0") int p,
                                           @RequestParam(value = "pz", required = false, defaultValue = "10") int pz) throws Exception {
        Result<List<CpInfo>> pages = new Result<>();
        int i = 1000;
        int j = 1000 / 0;
        pages.setData(cpInfoService.getByCondition(name, person, contact, m, p, pz));
        pages.setCode(116600);
        return pages;
    }


}
